package com.hguo.ribbon.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author leizi
 * @create 2023-04-15 21:37
 */
@RestController
public class TestController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @RequestMapping("/testChoose")
    public String testChoose(String serviceId) {
        ServiceInstance choose = loadBalancerClient.choose(serviceId);
        System.out.println(choose.getHost() + ":" + choose.getPort());
        return choose.toString();
    }

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/testRibbonBalance")
    public String testRibbonBalance(String serviceId) {
        // 直接用服务名称替换 ip:port
        String url = "http://" + serviceId + "/info";
        String forObject = restTemplate.getForObject(url, String.class);
        System.out.println(forObject);
        return forObject;
    }

}
